package com.rundatop.core.util;

import java.sql.Timestamp;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
    /**
     * 得到某年某周的第一天
     *
     * @param year
     * @param week
     * @return
     */
    public static Date getFirstDayOfWeek(int year, int week) {
        week = week - 1;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DATE, 1);

        Calendar cal = (Calendar) calendar.clone();
        cal.add(Calendar.DATE, week * 7);

        return getFirstDayOfWeek(cal.getTime());
    }

    /**
     * 得到某年某周的最后一天
     *
     * @param year
     * @param week
     * @return
     */
    public static Date getLastDayOfWeek(int year, int week) {
        week = week - 1;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DATE, 1);
        Calendar cal = (Calendar) calendar.clone();
        cal.add(Calendar.DATE, week * 7);

        return getLastDayOfWeek(cal.getTime());
    }

    /**
     * 取得当前日期年份
     *
     * @param date
     * @return
     */
    public static int getYearByDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }
    
    /**
     * 取得当前日期所在周的第一天
     *
     * @param date
     * @return
     */
    public static Date getFirstDayOfWeek(Date date) {
    	Calendar calendar = Calendar.getInstance();
    	calendar.setFirstDayOfWeek(Calendar.SUNDAY);
    	calendar.setTime(date);
    	calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); // Sunday
    	return calendar.getTime();
    }

    /**
     * 取得当前日期所在周的最后一天
     *
     * @param date
     * @return
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.SUNDAY);
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek() + 6); // Saturday
        return calendar.getTime();
    }

    /**
     * 取得当前日期所在周的前一周最后一天
     *
     * @param date
     * @return
     */
    public static Date getLastDayOfLastWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return getLastDayOfWeek(calendar.get(Calendar.YEAR), calendar.get(Calendar.WEEK_OF_YEAR) - 1);
    }

    /**
     * 返回指定日期的月的第一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getFirstDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
        return calendar.getTime();
    }

    /**
     * 返回指定年月的月的第一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getFirstDayOfMonth(Integer year, Integer month) {
        Calendar calendar = Calendar.getInstance();
        if (year == null) {
            year = calendar.get(Calendar.YEAR);
        }
        if (month == null) {
            month = calendar.get(Calendar.MONTH);
        }
        calendar.set(year, month, 1);
        return calendar.getTime();
    }

    /**
     * 返回指定日期的月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.getTime();
    }

    /**
     * 返回指定年月的月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfMonth(Integer year, Integer month) {
        Calendar calendar = Calendar.getInstance();
        if (year == null) {
            year = calendar.get(Calendar.YEAR);
        }
        if (month == null) {
            month = calendar.get(Calendar.MONTH);
        }
        calendar.set(year, month, 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.getTime();
    }

    /**
     * 返回指定日期的上个月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfLastMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) - 1, 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.getTime();
    }

    /**
     * 返回指定日期的季的第一天
     *
     * @param year
     * @param quarter
     * @return
     */
    public static Date getFirstDayOfQuarter(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return getFirstDayOfQuarter(calendar.get(Calendar.YEAR), getQuarterOfYear(date));
    }

    /**
     * 返回指定年季的季的第一天
     *
     * @param year
     * @param quarter
     * @return
     */
    public static Date getFirstDayOfQuarter(Integer year, Integer quarter) {
        Calendar calendar = Calendar.getInstance();
        Integer month = new Integer(0);
        if (quarter == 1) {
            month = 1 - 1;
        } else if (quarter == 2) {
            month = 4 - 1;
        } else if (quarter == 3) {
            month = 7 - 1;
        } else if (quarter == 4) {
            month = 10 - 1;
        } else {
            month = calendar.get(Calendar.MONTH);
        }
        return getFirstDayOfMonth(year, month);
    }

    /**
     * 返回指定日期的季的最后一天
     *
     * @param year
     * @param quarter
     * @return
     */
    public static Date getLastDayOfQuarter(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return getLastDayOfQuarter(calendar.get(Calendar.YEAR), getQuarterOfYear(date));
    }

    /**
     * 返回指定年季的季的最后一天
     *
     * @param year
     * @param quarter
     * @return
     */
    public static Date getLastDayOfQuarter(Integer year, Integer quarter) {
        Calendar calendar = Calendar.getInstance();
        Integer month = new Integer(0);
        if (quarter == 1) {
            month = 3 - 1;
        } else if (quarter == 2) {
            month = 6 - 1;
        } else if (quarter == 3) {
            month = 9 - 1;
        } else if (quarter == 4) {
            month = 12 - 1;
        } else {
            month = calendar.get(Calendar.MONTH);
        }
        return getLastDayOfMonth(year, month);
    }

    /**
     * 返回指定日期的上一季的最后一天
     *
     * @param year
     * @param quarter
     * @return
     */
    public static Date getLastDayOfLastQuarter(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return getLastDayOfLastQuarter(calendar.get(Calendar.YEAR), getQuarterOfYear(date));
    }

    /**
     * 返回指定年季的上一季的最后一天
     *
     * @param year
     * @param quarter
     * @return
     */
    public static Date getLastDayOfLastQuarter(Integer year, Integer quarter) {
        Calendar calendar = Calendar.getInstance();
        Integer month = new Integer(0);
        if (quarter == 1) {
            month = 12 - 1;
        } else if (quarter == 2) {
            month = 3 - 1;
        } else if (quarter == 3) {
            month = 6 - 1;
        } else if (quarter == 4) {
            month = 9 - 1;
        } else {
            month = calendar.get(Calendar.MONTH);
        }
        return getLastDayOfMonth(year, month);
    }

    /**
     * 返回指定日期的季度
     *
     * @param date
     * @return
     */
    public static int getQuarterOfYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) / 3 + 1;
    }

    /**
     * 日期转换
     * 
     * @param yyyymmddhhmmss
     *            时间字符串
     * @param format
     *            日期格式
     * @return
     */
    public static Date parseDate(String yyyymmddhhmmss, String format) {
        if (null == format) {
            throw new IllegalArgumentException("错误的日期格式");
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        try {
            ParsePosition pos = new ParsePosition(0);
            return formatter.parse(yyyymmddhhmmss, pos);
        } catch (Exception e) {
            throw new IllegalArgumentException("错误的日期:" + yyyymmddhhmmss + " " + e);
        }
    }

    /**
     * 日期转换成 Timestamp
     * 
     * @param yyyymmddhhmmss
     * @return
     */
    public static Timestamp parseTimestamp(String yyyymmddhhmmss) {
        try {
            return new Timestamp(parseDate(yyyymmddhhmmss).getTime());
        } catch (NullPointerException e) {
        }
        throw new IllegalArgumentException("日期为空或格式不正确");
    }

    /**
     * 字符串转换日期 日期格式为yyyy.MM.dd HH:mm:ss
     * 
     * @param yyyymmddhhmmss
     * @return
     */
    public static Date parseDate(String yyyymmddhhmmss) {
        if ((yyyymmddhhmmss == null) || (yyyymmddhhmmss.length() == 0)) {
            return null;
        }

        if ((yyyymmddhhmmss.indexOf("-") < 0) && (yyyymmddhhmmss.indexOf(".") < 0)
            && (yyyymmddhhmmss.indexOf("/") < 0)) {
            throw new IllegalArgumentException("错误的日期格式，应该有\"-\"或\".\"作为分隔符");
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        try {
            yyyymmddhhmmss = yyyymmddhhmmss.replace('-', '.');

            yyyymmddhhmmss = yyyymmddhhmmss.replace('/', '.');

            if (yyyymmddhhmmss.indexOf(":") < 0) {
                yyyymmddhhmmss = yyyymmddhhmmss + " 00:00:00";
            }
            ParsePosition pos = new ParsePosition(0);
            Date tempDat = formatter.parse(yyyymmddhhmmss, pos);
            if (tempDat == null)
                throw new IllegalArgumentException("错误的日期");
            return tempDat;
        } catch (Exception e) {
            throw new IllegalArgumentException("错误的日期:" + yyyymmddhhmmss + " " + e);
        }
    }

    /**
     * Date转换成格式为yyyy.MM.dd HH:mm:ss日期字符串
     * 
     * @param date
     * @return
     */
    public static String dateToString(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        try {
            return formatter.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("日期转换成字符串失败:" + e);
        }
    }

    /**
     * 日期转换
     * 
     * @param date
     *            日期
     * @param format
     *            格式
     * @return
     */
    public static String dateToString(Timestamp date, String format) {
        return dateToString((Date) date, format);
    }

    public static String dateToString(Date date, String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        try {
            return formatter.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("日期转换成字符串失败:" + e);
        }
    }

    /**
     * 当前日期字符串
     */

    public static String stringOfCnDateTime() {
        return stringOfCnDateTime(new java.util.Date());
    }

    public static String stringOfCnDateTime(java.util.Date date) {
        Format formatter = new SimpleDateFormat("yyyy年M月d日 H时m分s秒");
        return formatter.format(date);
    }

    /**
     * 当前日期字符串
     */
    public static String stringOfCnDate() {
        return stringOfCnDate(new java.util.Date());
    }

    public static String stringOfCnDate(java.util.Date date) {
        Format formatter = new SimpleDateFormat("yyyy年M月d日");
        return formatter.format(date);
    }

    /**
     * 当前日期字符串yyyy-MM-dd
     */
    public static String stringOfDate() {
        return stringOfDate(new java.util.Date());
    }

    public static String stringOfDate(java.util.Date date) {
        Format formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(date);
    }

    /**
     * 当前日期字符串yyyy-M-d
     */
    public static String stringOfDate2() {
        return stringOfDate2(new Date());
    }

    public static String stringOfDate2(Date date) {
        Format formatter = new SimpleDateFormat("yyyy-M-d");
        return formatter.format(date);
    }

    public static String stringOfDateTime() {
        return stringOfDateTime(new Date());
    }

    public static String stringOfDateTime(Date date) {
        return dateToString(date, "yyyy-MM-dd hh:mm:ss");
    }

    /**
     * 获取未来 第 days 天的日期 Date
     * 
     * @param days
     */
    public static Date getFetureDate(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + days);
        Date today = calendar.getTime();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        return format.parse(format.format(today), pos);
    }

    /**
     * date2比date1多的天数
     * 
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) {
            // 不同年
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    // 闰年
                    timeDistance += 366;
                } else {
                    // 不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else {
            // 同一年
            System.out.println("判断day2 - day1 : " + (day2 - day1));
            return day2 - day1;
        }
    }
    
    public static int computeHolidays(Date t1,Date t2) {
		//初始化第一个日期
		Calendar cal1 = Calendar.getInstance();
		//初始化第二个日期，这里的天数可以随便的设置
		Calendar cal2 = Calendar.getInstance();
		// 设置传入的时间格式  
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		// 指定一个日期  
		Date date1 = new Date();
		Date date2 = new Date();
		try {
			date1 = dateFormat.parse(dateFormat.format(t1));
			date2 = dateFormat.parse(dateFormat.format(t2));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		// 对 calendar 设置为 date 所定的日期  
		cal1.setTime(date1);  
		cal2.setTime(date2);

		int holidays = 0;
		//确定一个 大日期
		if(cal1.compareTo(cal2) > 0){
			Calendar temp = cal1;
			cal1 = cal2;
			cal2 = temp;
			temp = null;
		}
		while(cal1.compareTo(cal2)<=0){
			if(cal1.get(Calendar.DAY_OF_WEEK)==1||cal1.get(Calendar.DAY_OF_WEEK)==7){
				holidays++;
//				System.out.println("周末："+new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()));
			}
			cal1.add(Calendar.DAY_OF_YEAR,1);
			
		}
		return holidays;
	}
}
